import 'package:flutter/material.dart';
import 'package:safety_platform/components/hidden_danger.dart';
import 'package:safety_platform/components/Button.dart';
import 'package:safety_platform/models/hidden_danger.dart';
import 'package:safety_platform/models/situation.dart';
import 'package:safety_platform/models/attachment.dart';
import 'dart:io';
import 'package:safety_platform/theme.dart'
    show backgroundTitle, attachmentImage;
import 'package:safety_platform/pages/services.dart'
    show submitHiddenDangerVerified, uploadAttachment;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:safety_platform/utils.dart' show showErrorDialog;

import 'package:safety_platform/components/attachment.dart'
    show AttachmentPreviewGallery;

class VerificationPage extends StatefulWidget {
  final HiddenDanger hiddenDanger;
  final int hiddenDangerId;
  const VerificationPage({this.hiddenDanger, this.hiddenDangerId});
  State<StatefulWidget> createState() => _VerificationPageState(
      hiddenDanger: hiddenDanger, hiddenDangerId: hiddenDangerId);
}

class _VerificationPageState extends State<VerificationPage> {
  HiddenDanger hiddenDanger;
  int hiddenDangerId;
  bool _submitting = false;
  _VerificationPageState({this.hiddenDanger, this.hiddenDangerId});

  Widget _itemBuilder(BuildContext context, int index) {
    Situation situation = hiddenDanger.situations[index];
    List<Widget> children = [
      Flexible(
        flex: 1,
        child: Text(
          situation.content,
          // softWrap: false,
          overflow: TextOverflow.fade,
          maxLines: 8,
          style: Theme.of(context).textTheme.subhead,
        ),
      ),
    ];

    children.add(Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Text(
        '整改措施',
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: Theme.of(context).disabledColor,
        ),
      ),
    ));
    children.add(
      Text(
        situation.improvement,
        style: TextStyle(
          fontSize: 12,
          color: Theme.of(context).disabledColor,
        ),
      ),
    );

    return DecoratedBox(
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(
            width: 0.5,
            color: Color.fromARGB(251, 241, 241, 241),
          ))),
      child: Container(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        // height: 80,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: children,
        ),
      ),
    );
  }

  Widget _buildRecificationReport(HiddenDanger hiddenDanger) {
    if (hiddenDanger.attachments == null ||
        hiddenDanger.attachments.length <= 0) {
      return Container();
    }
   

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        backgroundTitle('整改报告'),
        DecoratedBox(
          child: AttachmentPreviewGallery(
            attachments: hiddenDanger.attachments,
            collapseLabel: '查看整改报告照片',
          ),
          decoration: BoxDecoration(
            color: Colors.white,
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("整改验收"),
        elevation: 0,

        //     leading: appLeading(context),
        backgroundColor: Color.fromARGB(255, 27, 130, 210),
        centerTitle: true, //设置标题是否局中
      ),
      body: SingleChildScrollView(child: _body()),
      bottomNavigationBar: _bottomVavigationBar(),
    );
  }

  Widget grllery(HiddenDanger hiddenDager) {
    if (hiddenDager.verifiedImages != null) {
      List<Widget> children = hiddenDager.verifiedImages.map((i) {
        Widget widget;
        if (i.uploadStatus != 'done') {
          widget = SizedBox(
            width: 80,
            height: 80,
            child: Stack(
              children: <Widget>[
                Image.file(
                  File(i.localPath),
                  width: 80,
                  height: 80,
                  fit: BoxFit.fill,
                ),
                new Opacity(
                  opacity: 0.5, //不透明度
                  child: new Container(
                      width: 80.0, height: 80.0, color: Colors.black),
                ),
                Center(
                  child: CircularProgressIndicator(
                    // semanticsLabel: '上传中',
                    // semanticsValue: '10%',
                    backgroundColor: Colors.white,
                    // value: 0.00,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    strokeWidth: 2,
                  ),
                )
                // CachedNetworkImage(
                //   imageUrl: i.localPath,
                // )
              ],
            ),
          );
        } else {
          if (i.localPath != null) {
            widget = Image.file(File(i.localPath),
                width: 80, height: 80, fit: BoxFit.fill);
          } else {
            widget = CachedNetworkImage(
              imageUrl: i.url,
              width: 80,
              height: 80,
              fit: BoxFit.fill,
              fadeInDuration: Duration(milliseconds: 200),
              fadeOutDuration: Duration(milliseconds: 200),
            );
          }
        }
        return Container(
          child: widget,
          margin: EdgeInsets.only(right: 8),
        );
      }).toList();
      return Container(
        margin: EdgeInsets.fromLTRB(16, 8, 16, 8),
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Container(
            child: Row(
              children: children,
              mainAxisAlignment: MainAxisAlignment.start,
            ),
          ),
        ),
      );
    }
    return Container();
  }

  Widget _buildVerificationWidget(HiddenDanger hiddenDanger) {
    Widget memoWidget = Container(
      padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
              bottom: BorderSide(
                  color: Color.fromARGB(255, 241, 241, 241), width: 0.5))),
      child: Column(
        
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          
          Padding(
              child: Text('验收备注',
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: Colors.grey,
                  )),
              padding: EdgeInsets.only(bottom: 8)),
          TextField(
            // maxLength: 150,
            maxLines: 4,
            textInputAction: TextInputAction.done,
            onSubmitted: ((val) => setState(() => hiddenDanger.memo = val)),
            decoration: InputDecoration(
                // labelText: '验收备注',
                // labelStyle: TextStyle(
                //   // color: Colors.grey,
                //   fontSize: 12,
                // ),

                filled: true,
                fillColor: Color.fromARGB(255, 241, 241, 241),
                border: InputBorder.none,
                contentPadding: EdgeInsets.all(6),
                hintText: '请填写验收备注,150字以内'),
          ),
        ],
      ),
    );
    return Container(
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          memoWidget,
          grllery(hiddenDanger),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 2),
                child: FlatButton.icon(
                  onPressed: () => _takePhone(),
                  icon: Icon(
                    Icons.camera_enhance,
                    color: Theme.of(context).primaryColor,
                  ),
                  label: Text('拍摄验收图片'),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  _takePhone() {
    ImagePicker.pickImage(source: ImageSource.camera).then((file) {
      if (file != null) {
        Attachment attachment = Attachment.fromLocal(file.path, file.path);
        if (hiddenDanger.verifiedImages == null) {
          hiddenDanger.verifiedImages = [];
        }
        if (mounted) {
          setState(() => hiddenDanger.verifiedImages.add(attachment));
        }
        uploadAttachment(attachment, target: 'risk.VerifiedImage')
            .then((attach) {
          if (mounted) {
            setState(() {
              attachment.id = attach.id;
              attachment.url = attach.url;
              attachment.contentType = attach.contentType;
              attachment.uploadStatus = 'done';
            });
          }
        });
      }
    });
  }

  Widget _body() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        HiddenDangerLiteWidget(hiddenDanger),
        backgroundTitle('存在的问题'),
        ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: hiddenDanger.situations.length,
          itemBuilder: (BuildContext context, int index) =>
              _itemBuilder(context, index),
        ),

        _buildRecificationReport(hiddenDanger),
        backgroundTitle('验收结果'),
        _buildVerificationWidget(hiddenDanger),
        // _t(),
        // _a()
      ],
    );
  }

  _submit() {
    if (hiddenDanger.verifiedImages != null) {
      if (hiddenDanger.verifiedImages.any((i) => i.uploadStatus != 'done')) {
        showErrorDialog(context, '错误', '还有图片未上传完成，请等待所有图片上传完成后再提交。', () {});
        return;
      }
    }
    setState(() {
      _submitting = true;
    });

    submitHiddenDangerVerified(hiddenDanger).then((HiddenDanger hiddenDanger) {
      Fluttertoast.showToast(msg: '提交成功');
      Navigator.of(context).pop(hiddenDanger);
      if (mounted) {
        setState(() {
          _submitting = false;
        });
      }
    }).catchError((e) {
      print(e);
      if (mounted) {
        setState(() {
          _submitting = false;
        });
      }
      showErrorDialog(context, '提交错误', e.message, () {});
      // throw e;
    });
  }

  _bottomVavigationBar() {
    // if (_task != null && _task.status == 'pending') {
    return Container(
        width: MediaQuery.of(context).size.width,
        height: 48,
        color: Colors.white,
        child: Button(
          loading: _submitting,
          buttonColor: Colors.white,
          onPressed: () {
            _submit();
          },
          text: '确认验收',
          textSize: 18,
          textColor: Color.fromARGB(255, 27, 130, 210),
        ));
  }
}
